package com.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.Scanner;

public class JDBCDemo {
    public static void showStudents(){
        try(Connection conn = DataSourceUtils.getConnection()){
            PreparedStatement ps = conn.prepareStatement("select * from student");
            ResultSet rs = ps.executeQuery();
            while (rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString("name");
                int age = rs.getInt("age");
                System.out.println(id + " " + name + " " + age);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    //搜索学生，输入学生名字的一部分，搜索出所有名字包含这个字符串的学生
    public static void SearchStudents(String stuName){
        try(Connection conn = DataSourceUtils.getConnection()){
            PreparedStatement ps = conn.prepareStatement("select * from student where name like ?");
            ps.setString(1, "%"+stuName+"%");
            ResultSet rs = ps.executeQuery();
            while (rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString("name");
                int age = rs.getInt("age");
                System.out.println(id + " " + name + " " + age);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        //showStudents();
//            Scanner sc = new Scanner(System.in);
//            System.out.println("请输入学生姓名的一部分: ");
//            String stuName = sc.nextLine();
//            SearchStudents("大");
//            JDBCUtils.update("insert into student(name,age,gender,idcard,address) values(?,?,?,?,?)","王大六",32,"男","543987456872938439","天津");
        List<Student> list = JDBCUtils.query(Student.class, "select * from student");
        for(Student stu : list){
            System.out.println(stu);
        }
    }
}
